package com.hym.hymlistview_x;

import com.hym.myrrefreshlistview.R;

import android.R.integer;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.DecelerateInterpolator;
import android.widget.AbsListView;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.Scroller;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.Toast;

public class HymListview extends ListView implements OnScrollListener {

	/** 保存起始的y值 */
	private float mLastY = -1;
	/***/
	private Scroller mScroller;
	/** Scoller 监听器 */
	private OnScrollListener mScrollListener;

	/** HeaderView */
	private HymListViewHeader mHeaderView;
	/** HeaderView内容的容器 */
	private RelativeLayout mHeaderViewContent;
	/** HeaderView的时间 */
	private TextView mHeaderTimeView;
	/** HeaderView的高度 */
	private int mHeaderViewHeight;
	/** 是否可以下拉刷新 */
	private boolean mEnablePullRefresh = true;
	/** 是否正在刷新状态 */
	private boolean mPullRefreshing = false;
	/** 更新或者加载数据的接口 */
	private IHYMListViewListener mListViewListener;
	private int mTotalItemCount;
	// for mScroller, scroll back from header or footer.
	private int mScrollBack;
	private final static int SCROLLBACK_HEADER = 0;
	private final static int SCROLLBACK_FOOTER = 1;
	/**回滚的延时时间*/
	private final static int SCROLL_DURATION = 400; 
	private final static float OFFSET_RADIO = 1.8f;

	public HymListview(Context context) {
		super(context);
		initView(context);
	}

	public HymListview(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView(context);
	}

	public HymListview(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initView(context);
	}

	private void initView(Context context) {
		mScroller = new Scroller(context, new DecelerateInterpolator());
		super.setOnScrollListener(this);
		mHeaderView = new HymListViewHeader(context);
		mHeaderViewContent = (RelativeLayout) mHeaderView
				.findViewById(R.id.xlistview_header_content);
		mHeaderTimeView = (TextView) mHeaderView
				.findViewById(R.id.xlistview_header_time);
		addHeaderView(mHeaderView);
		// init header height
		mHeaderView.getViewTreeObserver().addOnGlobalLayoutListener(
				new OnGlobalLayoutListener() {

					@Override
					public void onGlobalLayout() {
						mHeaderViewHeight = mHeaderViewContent.getHeight();
						getViewTreeObserver()
								.removeGlobalOnLayoutListener(this);
					}
				});
	}

	@Override
	public void setAdapter(ListAdapter adapter) {
		// TODO 需要对footerView进行处理
		super.setAdapter(adapter);
	}

	/**
	 * 设置下拉刷新是否可用
	 * 
	 * @param enable
	 */
	public void setPullRefreshEnable(boolean enable) {
		mEnablePullRefresh = enable;
		if (!mEnablePullRefresh) {
			// 设置不可用，隐藏内容布局
			mHeaderViewContent.setVisibility(View.INVISIBLE);
		} else {
			mHeaderViewContent.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 停止刷新，重设headerView
	 */
	public void stopRefresh() {
		if (mPullRefreshing == true) {
			mPullRefreshing = false;
			resetHeaderHeight();
		}
	}

	/**
	 * 设置HeaderView中的最后一次的更新时间
	 * 
	 * @param time
	 */
	public void setRrefreshTime(String time) {
		mHeaderTimeView.setText(time);
	}

	/**
	 * 更新HeaderView的高度
	 * 
	 * @param delta
	 */
	private void updateHeaderHeight(float delta) {
		mHeaderView.setVisibleHeight((int) delta
				+ mHeaderView.getVisiableHeight());
		Log.e("visableHeight",(int) delta
				+ mHeaderView.getVisiableHeight()+"" );
		// 未处于刷新状态，更新箭头
		if (mEnablePullRefresh && !mPullRefreshing) {
			if (mHeaderView.getVisiableHeight() > mHeaderViewHeight) {
				mHeaderView.setState(HymListViewHeader.STATE_READY);
			} else {
				mHeaderView.setState(HymListViewHeader.STATE_NORMAL);
			}
		}
		// 每次都滚到顶部
		setSelection(0);

	}

	/**
	 * 重设headerView的高度
	 */
	public void resetHeaderHeight() {
		int height = mHeaderView.getVisiableHeight();
		if(height==0)//没有显示的时候，直接return
			return;
		// 正在刷新和头部没有显示完全的时候，直接return
		int finalHeight=0;
		// 刷新状态，仅仅回到显示整个header的位置
		if(mPullRefreshing&&height>mHeaderViewHeight){
			finalHeight=mHeaderViewHeight;
		}
		mScrollBack = SCROLLBACK_HEADER;
		mScroller.startScroll(0, height, 0, finalHeight-height,SCROLL_DURATION);
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		
		if (mLastY == -1) {
			mLastY = ev.getRawY();
		}

		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			// 记录按下的位置
			mLastY = ev.getRawY();
			break;
		case MotionEvent.ACTION_MOVE:
			final float deltaY = ev.getRawY() - mLastY;
			mLastY = ev.getRawY();

			if (getFirstVisiblePosition() == 0
					&& mHeaderView.getVisiableHeight() > 0 ||deltaY>0) {
				updateHeaderHeight(deltaY / OFFSET_RADIO);
				//invokeOnScrolling();
			}/* else if()处理底部加载更多 */
			break;
		default:

			mLastY = -1; // reset
			if (getFirstVisiblePosition() == 0) {
				// invoke refresh
				if (mEnablePullRefresh
						&& mHeaderView.getVisiableHeight() > mHeaderViewHeight) {
					mPullRefreshing = true;
					mHeaderView.setState(HymListViewHeader.STATE_REFRESHING);
					if (mListViewListener != null) {
						mListViewListener.onRefresh();
					}
				}
				resetHeaderHeight();
			} /*
			 * else if (getLastVisiblePosition() == mTotalItemCount - 1) { //
			 * invoke load more. if (mEnablePullLoad &&
			 * mFooterView.getBottomMargin() > PULL_LOAD_MORE_DELTA &&
			 * !mPullLoading) { startLoadMore(); } resetFooterHeight(); }
			 */
			break;
		}
		return super.onTouchEvent(ev);
	}

	@Override
	public void computeScroll() {
		if (mScroller.computeScrollOffset()) {
			if (mScrollBack == SCROLLBACK_HEADER) {
				// 处理header逻辑
				mHeaderView.setVisibleHeight(mScroller.getCurrY());
			} else {
				// 处理footer逻辑
			}
		}
		postInvalidate();
		//invokeOnScrolling();
		super.computeScroll();
	}

	@Override
	public void setOnScrollListener(OnScrollListener l) {
		mScrollListener = l;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (mScrollListener != null) {
			mScrollListener.onScrollStateChanged(view, scrollState);
		}
	}

	/**
	 * view :The view whose scroll state is being reported firstVisibleItem :the
	 * index of the first visible cell (ignore if visibleItemCount == 0)
	 * visibleItemCount: the number of visible cells totalItemCount: the number
	 * of items in the list adaptor
	 */
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// 传递给用户的滚动监听器
		mTotalItemCount = totalItemCount;
		if (mScrollListener != null) {
			mScrollListener.onScroll(view, firstVisibleItem, visibleItemCount,
					totalItemCount);
		}
	}

//	/**
//	 * 唤起View的滚动
//	 */
//	private void invokeOnScrolling() {
//		if (mScrollListener instanceof OnHymScrollListener) {
//			OnHymScrollListener listener = (OnHymScrollListener) mScrollListener;
//			listener.onHymScrolling(this);
//		}
//
//	}

	/**
	 * 设置回调的监听器
	 * 
	 * @param listener
	 */
	public void setHymListViewListener(IHYMListViewListener listener) {
		mListViewListener = listener;
	}

	/**
	 * 数据操作的回调接口
	 */
	public interface IHYMListViewListener {
		/**
		 * 刷新数据的接口方法
		 */
		public void onRefresh();

		/**
		 * 加载数据的接口方法
		 */
		public void onLoadMore();
	}

	/**
	 * you can listen ListView.OnScrollListener or this one. it will invoke
	 * onXScrolling when header/footer scroll back.
	 */
	public interface OnHymScrollListener extends OnScrollListener {
		public void onHymScrolling(View view);
	}

}
